package com.myBlog.services.Remark;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myBlog.pojo.Remark;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
@EnableScheduling
public class RemarkCaches {

    // 缓存队列
    private static final String[] chacheQueue = {"remarkList_1","remarkList_2"};
    // 激活的缓存
    private static String cache_Name = chacheQueue[0];

    @Autowired
    private RemarkService remarkService;

    @Autowired
    private RedisTemplate redisTemplate;

    public Page<Remark> getCache(int pageNum, int pageSize){
        long size = redisTemplate.opsForList().size(cache_Name);
        Page<Remark> remarkPage = new Page<>();
        remarkPage.setCurrent(pageNum);
        remarkPage.setSize(pageSize);
        remarkPage.setTotal(size);
        // 暂时关闭评论分页
//        remarkPage.setRecords( redisTemplate.opsForList().range(cache_Name, (pageNum - 1) * pageSize, size <= (pageNum * pageSize - 1) ? size : (pageNum * pageSize - 1)) );
        remarkPage.setRecords( redisTemplate.opsForList().range(cache_Name, 0 , -1 ) );
        return remarkPage;
    }

    private void setCache(List<Remark> remarks, String cahcheName){
        redisTemplate.delete(cahcheName);
        if(!remarks.isEmpty()){
            redisTemplate.opsForList().rightPushAll(cahcheName,remarks);
        }
    }

    //900 000 即15分钟执行一次： 切换缓存key，并将数据库同步到redis
    @Scheduled(fixedDelay = 900000)
    public void scheduleCache(){
        log.info("评论缓存获取并切换缓存key定时任务开始：");
        List<Remark> remarks = remarkService.list( new QueryWrapper<Remark>().eq("status","1").orderByDesc("remark_time") );
        // 下一个被激活/投入使用的key
        String next_activeKey = null;
        for (int index=0;index<chacheQueue.length;index++){
            if(!chacheQueue[index].equals(cache_Name)){
                next_activeKey = chacheQueue[index];
                break;
            }
        }

        this.setCache(remarks,next_activeKey);
        cache_Name = next_activeKey;
        log.info("评论缓存获取并切换缓存key定时任务结束：");
    }

    // 缓存添加评论的key
    private static String saveRemarkCache = "remark_save";

    // 缓存同步数据库,10分钟(600,000ms)每次
    @Scheduled(fixedDelay = 600000)
    public void saveRemarksToDB(){
        log.info("评论缓存 存入数据库 定时任务开始：");
        List<Remark> remarkList = redisTemplate.opsForList().range(saveRemarkCache, 0, -1);
        if(!remarkList.isEmpty()){
            // 新增的评论列表没有id，而旧有的评论列表有id， saveBatch()根据有无id进行数据库更新或新增，或删除（数据库没有记录对得上缓存数据的id）。
            remarkService.saveBatch(remarkList);
            redisTemplate.delete(saveRemarkCache);
        }
        log.info("评论缓存 存入数据库 定时任务结束：");
        this.scheduleCache();
    }

    public void appendToCache(Remark remark){
        redisTemplate.opsForList().leftPush(saveRemarkCache,remark);
    }
}
